/*
 * Copyright (c) ycq_work@163.com
 */

package com.mxg.blog.controller.articleAdmin;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.mxg.blog.common.CqLogger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;

/**
 * @Author: ycq_work@163.com
 * @DATE: 2023/5/8 21:23
 * 生成验证码
 */
@Controller
public class CaptchaController {
    CqLogger logger = CqLogger.getInstance();

    //装配 DefaultKaptcha 生成验证码
    private final DefaultKaptcha captchaProducer;

    public CaptchaController(DefaultKaptcha captchaProducer) {
        this.captchaProducer = captchaProducer;
    }

    @GetMapping("api/captcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) throws Exception{
        //生成验证码
        String text = captchaProducer.createText();
        //生成带验证码的图片
        BufferedImage image = captchaProducer.createImage(text);

        //获取session 用以保存验证码
        HttpSession session = request.getSession(true);

        //保存验证码
        session.setAttribute("captcha", text);

        //debug 获取验证码, 用以打印出验证码日志
        logger.print("验证码已生成!");
        String captcha = (String) session.getAttribute("captcha");
        logger.print("验证码为: " + captcha);

        //设置session的有效期为5分钟
        session.setMaxInactiveInterval(300);

        //发送验证码
        response.setContentType("image/png");
        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(image, "png", outputStream);
        outputStream.close();
        logger.print("验证码已发送!");
    }
}
